package com.fujimana.rockincat.restree.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class RestreeFilter implements Filter {

	private List<Filter> filters;

	@Override
	public void destroy() {
		for (Filter filter : filters) {
			filter.destroy();
		}
	}
	
	public RestreeFilter(List<Filter> filters) {
		this.filters = filters;
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		for (Filter filter : filters) {
			filter.init(config);
		}

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		new FilterChainImpl(chain).doFilter(request, response);
	}

	private class FilterChainImpl implements FilterChain {

		private FilterChain chain;
		private int index;

		private FilterChainImpl(FilterChain chain) {
			this.chain = chain;
			index = -1;
		}

		@Override
		public void doFilter(ServletRequest request, ServletResponse response)
				throws IOException, ServletException {
			if (++index < filters.size()) {
				Filter filter = filters.get(index);

				filter.doFilter(request, response, this);
			} else {
				chain.doFilter(request, response);
			}
		}

	}
	
}
